var config = require('../config');
var fs = require('fs');
var path = require('path');
var moment = require('moment');
var then = require('thenjs');
var LogWriter = require('log-writer');
var pid = process.pid;
var ip = '127.0.0.1';
var mkdir = require('mkdir-p');
var lockFile = require('lockfile')
var lock = './file.lock';
var schedule = require('node-schedule');

mkdir.sync(config.logPath);
var types = ['track'];
for(var i =0; i< types.length; i++){
    mkdir.sync(config.targetPath+'/'+types[i]);
}

function checkFile(filename,cb){
    var filePath = path.join(config.logPath,filename);
    var tag = 'track';
    var randomName = getFileName(tag,6);
    var newPath= path.join(config.targetPath+'/'+tag,randomName);
    fs.exists(filePath, function (exists) {
        if(!exists)return;
        var readStream = fs.createReadStream(filePath)
        var writeStream = fs.createWriteStream(newPath+'.tmp');
        readStream.pipe(writeStream);
        readStream.on('end',function() {
            try{
                fs.unlinkSync(filePath);
                fs.rename(newPath+'.tmp',newPath,function(err){
                    if(err){
                        console.log("重命名失败！");
                    }else{
                        console.log("重命名成功！");
                    }
                });
            }catch(e){
                console.info('file read error',e);
            }
            cb&&cb(null);
        });
    });
}

function getFileName(type,len) {
    len = len || 6;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    var ary = [];
    var time = moment().format('YYYYMMDDHHmmss');
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    ary.push(type);
    ary.push(time);
    ary.push(ip);
    ary.push(pwd);
　　return ary.join('-');
}

var logCache = {};
logCache['track'] = [];

setInterval(function(){
    for(var i in logCache){
        var log = logCache[i].join('\n');
        logCache[i] = [];
        Writer(i,log);
    }
},500)

function Writer(type,str){
    if(!str)return;
    var name = config.logPath+['/%s',type,pid].join('_');
    var writer = new LogWriter(name+'.log');
    writer.writeln(str);
    writer.end();
}


lockFile.unlockSync(lock);
schedule.scheduleJob('0,30 * * * *', function(){
    setTimeout(function(){
        if(lockFile.checkSync(lock)){
            return;
        }
        lockFile.lockSync(lock);
        var files = fs.readdirSync(config.logPath);
        then.each(files,function(defer,filename){
            checkFile(filename,defer);
        }).then(function(){
            setTimeout(function(){
                lockFile.unlockSync(lock);
            },10*1000)
        }).fail(function (cont, error) {
            console.log('Error libs/log',error);
        });
    },Math.random()*3000)
});

exports.logger = function(dataObj) {
    try{
        logCache['track'].push(JSON.stringify(dataObj));
    }catch(e){
        console.info('log error',e);
    }
}  

exports.error = function(type,error) {
    var time = moment().format('YYYY-MM-DD HH:mm:ss');
    var msgAry = [time,type,error.toString()];
    var writer = new LogWriter(config.errorLogPath+'/error%s.log');
    writer.writeln(msgAry.join(' '));
    writer.end();
}


